package org.fastsyncer.worker;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;

/**
 * java.util.concurrent中实现的原子操作类包括：
 * AtomicBoolean、AtomicInteger、AtomicIntegerArray、AtomicLong、AtomicReference、
 * AtomicReferenceArray。
 */
public class ThreadCount {

	private static int thread = 100;
	private static CountDownLatch latch = new CountDownLatch(thread);

	private static AtomicInteger count = new AtomicInteger(0);
//	private static Integer count = 0;

	private static final ConcurrentHashMap<String, AtomicInteger> sync = new ConcurrentHashMap<>();

	@Test
	public void AtomicIntShow() throws InterruptedException {

		sync.put("excute", new AtomicInteger(0));
		sync.put("success", new AtomicInteger(0));
		
		System.out.println("AtomicIntShow() enter");
		ExecutorService es = Executors.newCachedThreadPool();

		for (int k = 0; k < thread; k++) {
			es.submit(new Runnable() {

				@Override
				public void run() {
					for (int k = 0; k < 100000; k++) {
						count.getAndAdd(1);
						AtomicInteger atomicInteger = sync.get("success");
						atomicInteger.getAndAdd(1);
						sync.put("success", atomicInteger);
					}
					latch.countDown();
				}

			});
		}

//		try {
//			Thread.sleep(1000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}

		// 使得主线程(main)阻塞直到latch.countDown()为零才继续执行
		latch.await();
		System.out.println("result of acumulated sum=" + count);
		es.shutdown();
		

		AtomicInteger excute = sync.get("excute");
		AtomicInteger success = sync.get("success");
		System.out.println("excute:"+excute);
		System.out.println("success:"+success);

	}
}
